using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;

namespace SharpErp.UI.Common
{
    public partial class CommonMultiSelectDialog : BaseDialogForm
    {
        public string KvKey { get; set; }

        public string SelectedText { get; set; }

        public HashSet<int> SelectedIds { get; set; }

        public bool MultiSelect { get; set; }

        public bool ReadOnly { get; set; }

        public List<Data.Common.Entity.GeneralInfoItem> DataSource { get; set; }

        private BindingList<Data.Common.Entity.GeneralInfoItem> Items { get; set; }

        void CommonMultiSelectDialog_AfterLoad(object sender, EventArgs e)
        {
            var selectedTextSet = new HashSet<string>();
            if (!string.IsNullOrEmpty(SelectedText))
            {
                foreach (var item in SelectedText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    selectedTextSet.Add(item.Trim());
                }
            }
            SelectedIds = new HashSet<int>();
            if (ReadOnly)
            {
                bar1.Visible = false;
                this.textBoxColumn.ReadOnly = true;
            }
            dgItems.AutoGenerateColumns = false;
            this.checkBoxColumn.Visible = MultiSelect;
            this.comboxColumn.Visible = !MultiSelect;
            this.checkBoxColumn.ValueType = this.comboxColumn.ValueType = typeof(bool);
            this.checkBoxColumn.ThreeState = this.comboxColumn.ThreeState = false;
            this.dgItems.CellClick += DgItems_CellClick;
            if (DataSource == null) Items = new BindingList<SharpErp.Data.Common.Entity.GeneralInfoItem>(Service.GetSysGeneralInfoItem(KvKey));
            else Items = new BindingList<SharpErp.Data.Common.Entity.GeneralInfoItem>(DataSource);
            dgItems.DataSource = Items;
            dgItems.Enabled = ReadOnly || true;
			foreach(DataGridViewRow row in dgItems.Rows)
			{
				var bindData = row.DataBoundItem as Data.Common.Entity.GeneralInfoItem;
				var checkBoxCell = row.Cells[0] as DataGridViewCheckBoxXCell;
				var radioBoxCell = row.Cells[1] as DataGridViewCheckBoxXCell;
				if(bindData == null || !selectedTextSet.Contains(bindData.Name.Trim())){
					checkBoxCell.Value = radioBoxCell.Value = false;
                    if(bindData != null) SelectedIds.Remove(bindData.Id);
				}else{
					checkBoxCell.Value= radioBoxCell.Value = true;
                    SelectedIds.Add(bindData.Id);
				}
			}
		}

        private void DgItems_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex == 0 || e.ColumnIndex == 1)
            {
                var cell = dgItems.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxXCell;
                if(cell.Value == null || cell.Value.ToString() == "False")
                {
                    cell.Selected = true;
                    cell.Value = true;
                    if (!MultiSelect)
                    {
                        for(int i = 0; i < dgItems.RowCount; ++i)
                        {
                            if (i == e.RowIndex) continue;
                            cell = dgItems.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxXCell;
                            cell.Value = false;
                            cell.Selected = false;
                        }
                    }
                }else
                {
                    cell.Selected = false;
                    cell.Value = false;
                }
            }
        }

        public CommonMultiSelectDialog()
        {
            InitializeComponent();
            AfterLoad += CommonMultiSelectDialog_AfterLoad;
        }
        
        private bool TrySaveUpdateData(){
        	if(!ReadOnly && dgItems.Enabled){
        		foreach(DataGridViewRow row in dgItems.Rows)
				{
					var bindData = row.DataBoundItem as Data.Common.Entity.GeneralInfoItem;
					if(bindData != null){
						if(String.IsNullOrEmpty(bindData.Name)){
							ToastNotificationUtil.ShowErrorToast(this, "名称不能为空！");
							return false;
						}
						if(bindData.Id > 0){
							Service.UpdateGeneralInfoItem(KvKey, bindData);
						}else{
							Service.AddGeneralInfoItem(KvKey, bindData);
						}
					}
        		}
        		dgItems.Enabled = false;
        	}
        	return true;
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
        	if(sender == buttonOk){
        		if(!TrySaveUpdateData()){
        			return;
        		}
        		SelectedText = "";
                SelectedIds.Clear();
 				foreach(DataGridViewRow row in dgItems.Rows)
				{
					var bindData = row.DataBoundItem as Data.Common.Entity.GeneralInfoItem;
                    DataGridViewCheckBoxXCell checkBoxCell = null;
					if(MultiSelect) checkBoxCell = row.Cells[0] as DataGridViewCheckBoxXCell;
					else checkBoxCell = row.Cells[1] as DataGridViewCheckBoxXCell;
					if(checkBoxCell.Value != null && Convert.ToBoolean(checkBoxCell.Value)){
						SelectedText += "," + bindData.Name.Trim();
						if(SelectedText[0] == ',') SelectedText = SelectedText.Substring(1);
                        SelectedIds.Add(bindData.Id);
					}
 				}
        		this.DialogResult = DialogResult.OK;
        		this.Close();
        	}else if(sender == buttonCancel){
        		this.DialogResult = DialogResult.Cancel;
        		this.Close();
        	}else if(sender == buttonReset){
        		CommonMultiSelectDialog_AfterLoad(null, null);
        	}
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
        	if(sender == buttonAdd){
        		Items.Add(new SharpErp.Data.Common.Entity.GeneralInfoItem(){Id=0, Name="输入名称"});
        		dgItems.Enabled = true;
        	}else if(sender == buttonModify){
        		if(dgItems.CurrentRow != null){
        			dgItems.Enabled = true;
        		}
        	}else if(sender == buttonDelete){
        		if(dgItems.CurrentRow != null){
        			var itemData = dgItems.CurrentRow.DataBoundItem as Data.Common.Entity.GeneralInfoItem;
        			if(itemData != null){
        				Service.DeleteGeneralInfoItem(KvKey, itemData.Id);
        				ToastNotificationUtil.ShowSuccessToast(this, "删除成功！");
        				Items.Clear();
        				Items = new BindingList<SharpErp.Data.Common.Entity.GeneralInfoItem>(Service.GetSysGeneralInfoItem(KvKey));
        				dgItems.DataSource = Items;
        				dgItems.Enabled = false;
        			}
        		}
        	}
        }
    }
}